package tools

import (
	"fmt"
	"log/slog"
	"strconv"
	"strings"
	"time"
)

var (
	location *time.Location
)

/* +8 time zone */
const TIME_ZONE_CHINA_BEIJING = "Asia/Shanghai"

/* +5.5 time zone */
const TIME_ZONE_CHINA_INDIA = "Asia/Kolkata"

func init() {
	//timeZone := "America/Puerto_Rico"
	SetTimeZone(TIME_ZONE_CHINA_BEIJING)

}
func SetTimeZone(timeZone string) {

	log := slog.With("timeZone", timeZone).With("now", time.Now().Format("2006-01-02 15:04:05 -0700 MST"))
	var err error
	location, err = time.LoadLocation(timeZone)
	if err != nil {
		// 失败时回退到系统本地时区
		location = time.Local
		log.Error("初始化时区失败")

	} else {
		time.Local = location // 设置全局时区
		log.Info("成功初始化时区为")
	}

	// 验证时区设置
	now := time.Now().In(location)

	log.Info("当前时区时间", "时间", now.String())
}

func NewNowTime() time.Time {
	time := time.Now().In(location)
	return time
}

func ParseTime(timeStr string) time.Time {
	ret, err := time.Parse("2006-01-02 15:04:05", timeStr)
	if err != nil {
		return time.Time{}
	}
	return ret
}
func ParseSecTime(secStr string) time.Time {
	sec, err := strconv.ParseInt(secStr, 10, 64)
	if err != nil {
		return NewNowTime()
	}
	rst := time.Unix(sec, 0)
	return rst
}

// 当前时间，格式为2024-02-24 03:44:06
func NewNowTimeStr() string {
	return NewNowTime().Format("2006-01-02 15:04:05")
}
func FormatDuration(d time.Duration) string {
	d = d.Round(time.Millisecond)
	days := d / (24 * time.Hour)
	d -= days * 24 * time.Hour
	hours := d / time.Hour
	d -= hours * time.Hour
	minutes := d / time.Minute
	d -= minutes * time.Minute
	seconds := d / time.Second
	d -= seconds * time.Second
	milliseconds := d / time.Millisecond

	var buf strings.Builder

	// 处理天
	if days > 0 {
		buf.WriteString(fmt.Sprintf("%dd", days))
	}

	// 处理小时
	if hours > 0 {
		buf.WriteString(fmt.Sprintf("%dh", hours))
	}

	// 处理分钟
	if minutes > 0 {
		buf.WriteString(fmt.Sprintf("%dm", minutes))
	}

	// 智能判断秒/毫秒格式
	switch {
	case days+hours+minutes > 0: // 当有更高单位时，显示秒+毫秒
		buf.WriteString(fmt.Sprintf("%d.%03ds", seconds, milliseconds))

	case seconds >= 1: // 仅有秒级时显示小数
		buf.WriteString(fmt.Sprintf("%d.%03ds", seconds, milliseconds))

	case milliseconds > 0: // 纯毫秒场景
		buf.WriteString(fmt.Sprintf("%dms", milliseconds))

	default: // 零值处理
		buf.WriteString("0ms")
	}

	return buf.String()
}
